package okex

import (
	"blockchain_data/handler/okex/api"
	"blockchain_data/middleware"
	"blockchain_data/utils"
	"blockchain_data/utils/errmsg"
	"container/list"
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"path"
	"sort"
	"time"
)


type OkFundingSave struct {
	middleware.SaveData
	CST *time.Location `json:"cst"`
}

func init()  {
	log = middleware.DataLogger()
}
func FundingRateInit(goods string, contractCode string, bourse string, server string,offset int) *OkFundingSave {

	okFundingSave := new(OkFundingSave)
	okFundingSave.CST = time.FixedZone("CST", offset * 3600)
	okFundingSave.Init(goods,contractCode,bourse,server,"")
	return okFundingSave
}

func (this *OkFundingSave)GetFunding() int {
	var startTime string
	timeTemplate1 := "2006-01-02T15:04:05.000Z" //常规类型
	file := fmt.Sprintf("%s/data/okex/%s/fundingrate/%s/fundingrate.csv",utils.GetCurrentPath(),this.Goods,this.ContractCode)
	if fileExist(file){
		//读取文件最后行
		lastLine := GetLastLine(file)
		lastLine_ts:= utils.StringToInt64(lastLine[0])
		startTime = time.Unix(int64(lastLine_ts/1000) + 60 *60, 0).In(this.CST).Format(timeTemplate1)
	}else {
		startTime = "2010-06-01T12:00:00.000Z"
	}
	start, _ := time.ParseInLocation(timeTemplate1, startTime, this.CST)
	start_mill := start.UnixNano()/1e6
	client := api.InitAPI()
	params := map[string]string{}
	params["instId"] = this.ContractCode
	params["before"] = utils.Int64ToString(start_mill)
	rep := client.GetFunding(params)
	sort.SliceStable(rep.Data, func(i, j int) bool {
		return utils.StringToInt(rep.Data[i].FundingTime) < utils.StringToInt(rep.Data[j].FundingTime)
	})
	if rep.Code == 200 {
		fundingrate_list := list.New()
		for _,fundingrate := range rep.Data{
			ts := fundingrate.FundingTime
			bourse := "okex"
			rate := fundingrate.RealizedRate
			next_rate := fundingrate.FundingRate
			ts8 :=utils.StrMillToTime(ts,"2006-01-02D15:04:05.000000",this.CST)
			s := fmt.Sprintf("%s,%s,%s,%s,%s,%s\n",ts,bourse,this.ContractCode,rate,next_rate,ts8)
			fundingrate_list.PushBack(s)
		}
		this.saveFundingRate(fundingrate_list)
		return errmsg.SUCCESS
	}else {
		return errmsg.ERROR
	}
}
//保存数据
func (this *OkFundingSave)saveFundingRate(fundingrate_list *list.List)  {
	file := fmt.Sprintf("%s/data/okex/%s/fundingrate/%s/fundingrate.csv",utils.GetCurrentPath(),this.Goods,this.ContractCode)
	// 文件不存在就创建
	if !fileExist(file){
		os.MkdirAll(path.Dir(file),os.ModePerm)
	}
	writer, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Error("保存数据出错. %v\n", err)
	}
	defer writer.Close()
	for e := fundingrate_list.Front(); e != nil; e = e.Next() {
		_, err := writer.Write([]byte(e.Value.(string)))
		if err != nil {
			log.Error("保存数据出错, %v\n", err)
		}
	}
}

// 判断文件是否存在
func fileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}

//获取文件最后一行
func GetLastLine(fileName string)  []string{
	f, err := os.Open(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	r := csv.NewReader(f)
	var lastLine []string
	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		lastLine = record
	}
	return lastLine
}

